package main

import (
	"fmt"
	"net"
)


func TcpSocketStart(addr string) {
	//定义一个tcp断点
	var tcpAddr *net.TCPAddr
	//通过ResolveTCPAddr实例一个具体的tcp断点
	tcpAddr, _ = net.ResolveTCPAddr("tcp", addr)
	//打开一个tcp断点监听
	tcpListener, _ := net.ListenTCP("tcp", tcpAddr)
	defer tcpListener.Close()

	//循环接收客户端的连接，创建一个协程具体去处理连接
	for {
		tcpConn, err := tcpListener.AcceptTCP()
		if err != nil {
			fmt.Println(err)
			continue
		}

		go tcpPipe(tcpConn)
	}
}

//具体处理连接过程方法
func tcpPipe(conn *net.TCPConn) {

	//tcp连接的地址
	ipStr := conn.RemoteAddr().String()
	fmt.Printf("tcpPipe ip=%s\n" ,ipStr)
	defer func() {
		fmt.Printf("websocket  err recover()") //有效
		fmt.Println(recover()) //有效

		conn.Close()

	}()

    for {
        var tcpbuf [1024]byte
		tcpbufLen, err := conn.Read(tcpbuf[:])
 
        if err != nil {
			fmt.Printf("tcpPipe err,ip=%s err: %v\n",ipStr, err)
            break
        }
		conn.Write(tcpbuf[:tcpbufLen])
		fmt.Printf("tcpPipe read,ip=%s,data: %v\n", ipStr, tcpbuf[:tcpbufLen])
    }
}

func main() {


	soketAddr:=":9911"

	go TcpSocketStart(soketAddr)

	select {}
}

